package com.tnl.utils;

import java.io.File;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.tnl.app.config.GlobalConfig;

public class MailUtils {
	public static String sendAttachmentMail(String to, String subject,String content,String filePath)
	   {
		 System.out.println(" enter sendMail function Step1");
	     JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
	     
	     senderImpl.setHost(GlobalConfig.MAILHOST);
	     
	 
	     //SimpleMailMessage mailMessage = new SimpleMailMessage();

	     Properties prop = new Properties();
	     prop.put(" mail.smtp.auth ", " true ");
	     prop.put(" mail.smtp.timeout ", " 25000 ");
	     senderImpl.setJavaMailProperties(prop);
	     senderImpl.setUsername(GlobalConfig.MAILUID);
	     senderImpl.setPassword(GlobalConfig.MAILKEY);
	  
	     
	     MimeMessage mailMessage= senderImpl.createMimeMessage();
	     
	 
	     try {
	    	 mailMessage.setRecipients(javax.mail.Message.RecipientType.TO, to);
	    	 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
		     mailMessage.setFrom(new InternetAddress(GlobalConfig.MAILUID));
		     mailMessage.setSubject(subject);
		     StringBuffer messageText=new StringBuffer();//内容以html格式发送,防止被当成垃圾邮件
		     messageText.append(content);
		     mailMessage.setContent(messageText.toString(), "text/html;charset=gb2312");
		     if (filePath!="") {
		    	 FileSystemResource file = new FileSystemResource(new File(filePath));
			     String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
		         messageHelper.addAttachment(fileName,file);
		     }
		     
		     senderImpl.send(mailMessage);
		     System.out.println(" 邮件发送成功.. ");
	     } catch (MessagingException e) {
	 		// TODO Auto-generated catch block
	 		e.printStackTrace();
	 	}
		return "Success";
	   }
	 
	 
	 public static void main(String[] args) {
		//MailUtils.sendMail("1194625637@qq.com", "MedTalent医人才登录密码", "亲爱的，您好！<br/>您的注册信息审核通过，账号角色：user.getRoleNames()，登录账号为user.getLoginName()，初始登录密码为：123456  <br/>复制链接：https://www.headoffer.com/hrplus，在电脑端登录系统！<br/> \r\n登录后请尽快修改初始密码！");
	}

}
